import com.asisto.model.User
import com.asisto.model.Role
import grails.util.Environment

class BootStrap {

    def authenticateService

     def init = { servletContext ->

        switch (Environment.current) {

            case Environment.DEVELOPMENT:
                createTestingUsers()
                println "Desarrollo"
                break;

            case Environment.PRODUCTION:
                println "No special configuration required"
                break;

        }


     }
     def destroy = {
     }


     void createTestingUsers()  {

            def samples = [
                           'lsabin' : [ userRealName: 'Leandro Sabin', email:'sabin.leandro@gmail.com'],
                           'admin' : [ userRealName: 'Administrador', email:'asistogal@gmail.com']
            ]

            def userRole = new Role(authority: "ROLE_USER", description: "Registered user")
            def adminRole = new Role(authority: "ROLE_ADMIN", description: "Admin user")

            def now = new Date()

            println "authenticateService : $authenticateService"

            

            if (!User.list()) {
                samples.each { userId, profileAttrs ->

                    println "user: $userId"
                    println "attrs: $profileAttrs"

                    def user = new User(username: userId 
                        , passwd: authenticateService.encodePassword("1234")
                        , userRealName: profileAttrs.userRealName,
                        , email: profileAttrs.email
                        , enabled: true
                        , emailShow: true
                    )

                    if ("admin" == userId) {
                        adminRole.addToPeople(user)
                    }

                    userRole.addToPeople(user)

                    if (user.validate()) {
                        println "Creando usuario ${userId}..."
                        user.save(flush:true)
                    } else {
                        println("\n\n\nError in account bootstrap for ${userId}!\n\n\n")
                        user.errors.each {err ->
                            println err
                        }
                    }

                }

                userRole.save()
                adminRole.save()

            }

     }


} 